/*
 * CreatGifViewController
 * @description 本文件提供对话中魔法工具箱中的闪光字的viewcontroller
 * @package
 * @author
 * @copyright
 * @version 		1.0
 * @description 本文件提供对话中魔法工具箱中的闪光字的viewcontroller
 */


#import "CreatGifViewController.h"
#import "SCGIFImageView.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "TKLoadingView.h"
#import "SDImageCache.h"
#import "BanBu_ChatViewController.h"
#import "BanBu_NavButton.h"
#import "BanBu_ImageView.h"

@interface CreatGifViewController ()

@end

@implementation CreatGifViewController
-(void)dealloc
{
    
    [_textLabel release],_textLabel = nil;
    self.inputView1 = nil;
    self.scImageView = nil;
    [super dealloc];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    [super viewWillAppear:animated];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    BanBu_ImageView * img1 = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable]autorelease];
    
    img1.frame = CGRectMake(0, 0, __MainScreen_Width, __MainScreen_Height);
    
    [self.view addSubview:img1];
    
    [self setUpForDismissKeyboard];//收缩键盘
    self.title = NSLocalizedString(@"sparkBtn", nil);
    self.chat.isColseKeyboard = NO;
    
    //返回
    BanBu_NavButton *btn_send=[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    btn_send.position = ButtonPositionRight;
    
    btn_send.frame=CGRectMake(0, 0, 50, 30);
    
    [btn_send setTitle:NSLocalizedString(@"sendReply", nil) forState:UIControlStateNormal];
    [btn_send addTarget:self action:@selector(sendMsg) forControlEvents:UIControlEventTouchUpInside];
    btn_send.titleLabel.font = [UIFont systemFontOfSize:14];
    
    
    self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithCustomView:btn_send]autorelease];
    
    _inputView1 = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300,85)];
    _inputView1.textColor = [UIColor blackColor];
    self.inputView1.font = [UIFont systemFontOfSize:18];
    _inputView1.layer.borderColor = [[UIColor grayColor] CGColor];
    _inputView1.layer.borderWidth = 1.0;
    _inputView1.layer.cornerRadius = 4.0;
    _inputView1.delegate = self;
    
    
    self.inputView1.returnKeyType = UIReturnKeyDefault;
    self.inputView1.keyboardType = UIKeyboardTypeDefault;
    
    
    [self.view addSubview:self.inputView1];
    [_inputView1 release];
    
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 300,25)];
    label.text = NSLocalizedString(@"sparkText", nil);
    label.textAlignment = kTextAlignmentLeft;
    label.numberOfLines = 1;
    label.textColor = [UIColor darkGrayColor];
    label.alpha = 0.6;
    _textLabel = label;
    [_inputView1 addSubview:_textLabel];
    [label release];
    
    
    UIButton *randomButton = [UIButton buttonWithType:UIButtonTypeCustom];
    randomButton.frame = CGRectMake(31, 110, 72, 30);
    [randomButton setBackgroundImage:[UIImage imageNamed:@"waveshan.png"] forState:UIControlStateNormal];
    randomButton.tag = 22223;
    [randomButton addTarget:self action:@selector(setStyleOfText:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:randomButton];
    
    UIButton *waveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    waveButton.frame = CGRectMake(randomButton.frame.origin.x + 21 + randomButton.frame.size.width, 110, 72, 30);
    [waveButton setBackgroundImage:[UIImage imageNamed:@"suijishan.png"] forState:UIControlStateNormal];
    waveButton.tag = 22224;
    [waveButton addTarget:self action:@selector(setStyleOfText:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:waveButton];
    
    UIButton *jumpButton = [UIButton buttonWithType:UIButtonTypeCustom];
    jumpButton.frame = CGRectMake(waveButton.frame.origin.x + 21 + waveButton.frame.size.width, 110, 72, 30);
    [jumpButton setBackgroundImage:[UIImage imageNamed:@"jumpshan.png"] forState:UIControlStateNormal];
    jumpButton.tag = 22225;
    [jumpButton addTarget:self action:@selector(setStyleOfText:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:jumpButton];
    
    SCGIFImageView *imageview = [[SCGIFImageView alloc] initWithFrame:CGRectMake(10, 170, 300, __MainScreen_Height-44-220-10-10)];
    
    _scImageView = imageview;
    [self.view addSubview:_scImageView];
    [imageview release];
    
    UIActivityIndicatorView *acity = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
    acity.hidesWhenStopped = YES;
    acity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    acity.color = [UIColor darkGrayColor];
    acity.center = CGPointMake(160,_scImageView.center.y-30);
    _activity = acity;
    [self.view addSubview:acity];
    [acity release];
}

-(void)popself
{
    [self.navigationController popToViewController:self.chat animated:YES];
}

-(void)setStyleOfText:(UIButton *)sender
{
    [_inputView1 resignFirstResponder];
    
    if(_inputView1.text.length)
    {
        if(currentUrl.length)
            [currentUrl release];
        if(sender.tag ==22223)
        {
            sparkStyle = TextSparkStytleWave;
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:_inputView1.text,@"flashtext",@"wave",@"flashmode",nil];
            _manager = [SDWebImageManager sharedManager];
            currentUrl = [[AppComManager creatGifDataURL:BanBu_Get_Flash_text par:dic] retain];
            NSLog(@"currentUrl1:%@",currentUrl);
            currentUrl = [NSString stringWithContentsOfURL:[NSURL URLWithString:currentUrl] encoding:NSUTF8StringEncoding error:nil];
            NSLog(@"currentUrl2:%@",currentUrl);
            [_manager downloadWithURL:[NSURL URLWithString:currentUrl] delegate:self];
        }
        else if(sender.tag ==22225)
        {
            sparkStyle = TextSparkStytleJump;
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:_inputView1.text,@"flashtext",@"jump",@"flashmode",nil];
            _manager = [SDWebImageManager sharedManager];
            currentUrl = [[AppComManager creatGifDataURL:BanBu_Get_Flash_text par:dic]retain];
            
            currentUrl = [NSString stringWithContentsOfURL:[NSURL URLWithString:currentUrl] encoding:NSUTF8StringEncoding error:nil];
            
            [_manager downloadWithURL:[NSURL URLWithString:currentUrl] delegate:self];
        }
        else
        {
            sparkStyle = TextSparkStytleRand;
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:_inputView1.text,@"flashtext",@"rand",@"flashmode",nil];
            _manager = [SDWebImageManager sharedManager];
            currentUrl = [[AppComManager creatGifDataURL:BanBu_Get_Flash_text par:dic]retain];
            
            currentUrl = [NSString stringWithContentsOfURL:[NSURL URLWithString:currentUrl] encoding:NSUTF8StringEncoding error:nil];
            
            [_manager downloadWithURL:[NSURL URLWithString:currentUrl] delegate:self];
        }
        [_activity startAnimating];
        [_inputView1 resignFirstResponder];
        self.view.userInteractionEnabled = NO;
        
    }
    else
    {
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"kongAlert", nil) activityAnimated:NO duration:1];
    }
    
}
-(void)sendMsg
{
    if(_scImageView.image)
    {
        NSMutableDictionary * picDictionary = [NSMutableDictionary dictionaryWithCapacity:5];
        [picDictionary setValue:self.gifFilePath forKey:@"image"];
        [picDictionary setValue:@"gif" forKey:@"filetype"];
        [picDictionary setValue:[NSNumber numberWithInt:ChatCellTypeImage] forKey:KeyType];
        [picDictionary setValue:@"mg" forKey:KeyShowFrom];
        
        if(_inputView1.text.length)
        {
            [[NSNotificationCenter defaultCenter]postNotificationName:kSendMsgAllTypeNotification object:picDictionary];
            
            self.chat.isColseKeyboard = YES;
            
            //返回对话界面
            [self popself];
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"kongAlert", nil) activityAnimated:NO duration:1];
        }
        
    }
    else if(!_inputView1.text.length)
    {
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"sparkText", nil) activityAnimated:NO duration:1];
    }
    else if(!_scImageView.image)
    {
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"chooseSparkEfficiency", nil) activityAnimated:NO duration:1];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
#pragma SDWebImageDelegate
-(void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image forURL:(NSURL *)url
{
    [_activity stopAnimating];
    self.view.userInteractionEnabled = YES;
    
    NSData * data = [NSData dataWithContentsOfURL:url];
    
    [[SDImageCache sharedImageCache] MsgStoreKeyWithDataToDisk:@[[NSString stringWithFormat:@"%@",url],data]];
    
    [_scImageView setGifData:[NSData dataWithContentsOfFile:[[SDImageCache sharedImageCache] msgCachePathForKey:[NSString stringWithFormat:@"%@",url]]]];
    
    _scImageView.frame = CGRectMake(20, 180, _scImageView.image.size.width, _scImageView.image.size.height);
    _scImageView.center = CGPointMake(__MainScreen_Width/2, 170+ (__MainScreen_Height-170)/3);
    
    self.gifFilePath = [NSString stringWithFormat:@"%@",url];
}

-(void)webImageManager:(SDWebImageManager *)imageManager didFailWithError:(NSError *)error
{
    [_activity stopAnimating];
    self.view.userInteractionEnabled = YES;
    [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:1];
}
#pragma UItextViewDelegate
-(void)textViewDidChange:(UITextView *)textView
{
    _textLabel.hidden = _inputView1.text.length?YES:NO;
}

#pragma show and hide the keyboard
- (void)setUpForDismissKeyboard {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(tapAnywhereToDismissKeyboard:)];
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view removeGestureRecognizer:singleTapGR];
                }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    //此method会将self.view里所有的subview的first responder都resign掉
    [self.view endEditing:YES];
}


@end
